import type { App } from 'vue';

/**
 * 按钮波浪指令
 * @directive 默认方式：v-waves，如 `<div v-waves></div>`
 * @directive 参数方式：v-waves=" |light|red|orange|purple|green|teal"，如 `<div v-waves="'light'"></div>`
 */
export function wavesDirective(app: App) {
	app.directive('waves', {
		mounted(el, binding) {
			el.classList.add('waves-effect');
			binding.value && el.classList.add(`waves-${binding.value}`);
			function setConvertStyle(obj: { [key: string]: unknown }) {
				let style: string = '';
				for (let i in obj) {
					if (obj.hasOwnProperty(i)) style += `${i}:${obj[i]};`;
				}
				return style;
			}
			function onCurrentClick(e: { [key: string]: unknown }) {
				let elDiv = document.createElement('div');
				elDiv.classList.add('waves-ripple');
				el.appendChild(elDiv);
				let styles = {
					left: `${e.layerX}px`,
					top: `${e.layerY}px`,
					opacity: 1,
					transform: `scale(${(el.clientWidth / 100) * 10})`,
					'transition-duration': `750ms`,
					'transition-timing-function': `cubic-bezier(0.250, 0.460, 0.450, 0.940)`,
				};
				elDiv.setAttribute('style', setConvertStyle(styles));
				setTimeout(() => {
					elDiv.setAttribute(
						'style',
						setConvertStyle({
							opacity: 0,
							transform: styles.transform,
							left: styles.left,
							top: styles.top,
						})
					);
					setTimeout(() => {
						elDiv && el.removeChild(elDiv);
					}, 750);
				}, 450);
			}
			el.addEventListener('mousedown', onCurrentClick, false);
		},
		unmounted(el) {
			el.addEventListener('mousedown', () => {});
		},
	});
}

/**
 * 自定义拖动指令
 * @description  使用方式：v-drag="[dragDom,dragHeader]"，如 `<div v-drag="['.drag-container .el-dialog', '.drag-container .el-dialog__header']"></div>`
 * @description dragDom 要拖动的元素，dragHeader 要拖动的 Header 位置
 * @link 注意：https://github.com/element-plus/element-plus/issues/522
 * @lick 参考：https://blog.csdn.net/weixin_46391323/article/details/105228020?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-10&spm=1001.2101.3001.4242
 */
export function dragDirective(app: App) {
	app.directive('drag', {
		mounted(el, binding) {
			if (!binding.value) return false;

			const dragDom = document.querySelector(binding.value[0]) as HTMLElement;
			const dragHeader = document.querySelector(binding.value[1]) as HTMLElement;

			dragHeader.onmouseover = () => (dragHeader.style.cursor = `move`);

			function down(e: any, type: string) {
				// 鼠标按下，计算当前元素距离可视区的距离
				const disX = type === 'pc' ? e.clientX - dragHeader.offsetLeft : e.touches[0].clientX - dragHeader.offsetLeft;
				const disY = type === 'pc' ? e.clientY - dragHeader.offsetTop : e.touches[0].clientY - dragHeader.offsetTop;

				// body当前宽度
				const screenWidth = document.body.clientWidth;
				// 可见区域高度(应为body高度，可某些环境下无法获取)
				const screenHeight = document.documentElement.clientHeight;

				// 对话框宽度
				const dragDomWidth = dragDom.offsetWidth;
				// 对话框高度
				const dragDomheight = dragDom.offsetHeight;

				const minDragDomLeft = dragDom.offsetLeft;
				const maxDragDomLeft = screenWidth - dragDom.offsetLeft - dragDomWidth;

				const minDragDomTop = dragDom.offsetTop;
				const maxDragDomTop = screenHeight - dragDom.offsetTop - dragDomheight;

				// 获取到的值带px 正则匹配替换
				let styL: any = getComputedStyle(dragDom).left;
				let styT: any = getComputedStyle(dragDom).top;

				// 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
				if (styL.includes('%')) {
					styL = +document.body.clientWidth * (+styL.replace(/\%/g, '') / 100);
					styT = +document.body.clientHeight * (+styT.replace(/\%/g, '') / 100);
				} else {
					styL = +styL.replace(/\px/g, '');
					styT = +styT.replace(/\px/g, '');
				}

				return {
					disX,
					disY,
					minDragDomLeft,
					maxDragDomLeft,
					minDragDomTop,
					maxDragDomTop,
					styL,
					styT,
				};
			}

			function move(e: any, type: string, obj: any) {
				let { disX, disY, minDragDomLeft, maxDragDomLeft, minDragDomTop, maxDragDomTop, styL, styT } = obj;

				// 通过事件委托，计算移动的距离
				let left = type === 'pc' ? e.clientX - disX : e.touches[0].clientX - disX;
				let top = type === 'pc' ? e.clientY - disY : e.touches[0].clientY - disY;

				// 边界处理
				if (-left > minDragDomLeft) {
					left = -minDragDomLeft;
				} else if (left > maxDragDomLeft) {
					left = maxDragDomLeft;
				}

				if (-top > minDragDomTop) {
					top = -minDragDomTop;
				} else if (top > maxDragDomTop) {
					top = maxDragDomTop;
				}

				// 移动当前元素
				dragDom.style.cssText += `;left:${left + styL}px;top:${top + styT}px;`;
			}

			/**
			 * pc端
			 * onmousedown 鼠标按下触发事件
			 * onmousemove 鼠标按下时持续触发事件
			 * onmouseup 鼠标抬起触发事件
			 */
			dragHeader.onmousedown = (e) => {
				const obj = down(e, 'pc');
				document.onmousemove = (e) => {
					move(e, 'pc', obj);
				};
				document.onmouseup = () => {
					document.onmousemove = null;
					document.onmouseup = null;
				};
			};

			/**
			 * 移动端
			 * ontouchstart 当按下手指时，触发ontouchstart
			 * ontouchmove 当移动手指时，触发ontouchmove
			 * ontouchend 当移走手指时，触发ontouchend
			 */
			dragHeader.ontouchstart = (e) => {
				const obj = down(e, 'app');
				document.ontouchmove = (e) => {
					move(e, 'app', obj);
				};
				document.ontouchend = () => {
					document.ontouchmove = null;
					document.ontouchend = null;
				};
			};
		},
	});
}

/**
 * 防止重复点击提交按钮
 * @directive 默认方式：v-reclick，如 `<el-button v-reclick></el-button>`
 * @directive 参数方式：v-reclick="number"，如 `<el-button v-reclick="500"></el-button>`
 */
export function reclickDirective(app: App) {
	app.directive('reclick', {
		mounted(el: any, time: any) {
			el.addEventListener('click', () => {
				if (!el.disabled) {
					el.disabled = true;
					setTimeout(
						() => {
							el.disabled = false;
						},
						time.value === undefined ? 500 : time.value
					);
				}
			});
		},
		unmounted(el: any) {
			el.disabled = false;
		},
	});
}

/**
 * 自定义拖动分隔条指令，用于动态调整两个相邻元素的宽度
 * @description 使用方式：v-resize="[leftElementSelector, rightElementSelector, maxRightWidth]"
 * @description leftElementSelector 左侧要调整宽度的元素的 CSS 选择器
 * @description rightElementSelector 右侧要调整宽度的元素的 CSS 选择器
 * @description maxRightWidth 右侧元素的最大宽度，可选参数，默认无限制
 *
 * @example
 * <div class="flex-container">
 *   <div class="component-left">Left Component</div>
 *   <div class="divide-box" v-resize="['.component-left', '.component-right', 300]" ref="divideRef"></div>
 *   <div class="component-right">Right Component</div>
 * </div>
 *  如果要重置高度 (divideRef.value as any).changeHeight()
 */
export function resizeDirective(app: App) {
	/**
	 * 注册名为 'resize' 的自定义指令
	 */
	app.directive('resize', {
		/**
		 * 指令挂载时的钩子函数
		 * @param el 指令绑定的元素，即分隔条元素
		 * @param binding 包含指令相关信息的对象，其中 value 是传入的参数数组
		 */
		mounted(el: HTMLElement, binding: { value: string[] | [string, string, number] }) {
			// 若未传入参数，直接返回
			if (!binding.value) return false;

			// 获取父元素的高度并设置给拖拽元素
			const parentElement = el.parentNode as HTMLElement;
			const initialHeight = parentElement.offsetHeight;
			el.style.height = `${initialHeight}px`;
			// 为拖拽元素添加默认样式
			el.style.width = '5px';
			el.style.flexShrink = '0';
			el.style.backgroundColor = '#ccc';
			el.style.cursor = 'col-resize';
			el.style.transition = 'background-color 0.3s, box-shadow 0.3s';

			// 通过选择器获取左侧和右侧的元素
			const leftComponent = document.querySelector(binding.value[0]) as HTMLElement;
			const rightComponent = document.querySelector(binding.value[1]) as HTMLElement;

			// 获取右侧元素的最大宽度，若未传入则默认为 Infinity
			const maxRightWidth = binding.value.length > 2 ? Number(binding.value[2]) : Infinity;

			// 鼠标悬停时添加样式
			el.onmouseover = () => {
				el.style.backgroundColor = '#999';
				el.style.boxShadow = '0 0 5px rgba(0, 0, 0, 0.3)';
				el.style.cursor = 'move';
			};

			// 鼠标移出时恢复默认样式
			el.onmouseout = () => {
				el.style.backgroundColor = '#ccc';
				el.style.boxShadow = 'none';
				el.style.cursor = 'col-resize';
			};

			// 鼠标按下时添加样式
			el.onmousedown = (e: MouseEvent) => {
				el.style.backgroundColor = '#666';
				const obj = down(e);
				document.onmousemove = (e: MouseEvent) => {
					move(e, obj);
				};
				document.onmouseup = () => {
					el.style.backgroundColor = '#ccc';
					// 鼠标抬起时，移除鼠标移动和抬起事件监听器
					document.onmousemove = null;
					document.onmouseup = null;
				};
				disableSelection();
			};

			// 触摸开始时添加样式
			el.ontouchstart = (e: TouchEvent) => {
				el.style.backgroundColor = '#666';
				const obj = down(e);
				document.ontouchmove = (e: TouchEvent) => {
					move(e, obj);
				};
				document.ontouchend = () => {
					el.style.backgroundColor = '#ccc';
					// 手指移开时，移除触摸移动和结束事件监听器
					document.ontouchmove = null;
					document.ontouchend = null;
				};
				disableSelection();
			};

			/**
			 * 鼠标或手指按下时的处理函数
			 * @param e 鼠标或触摸事件对象
			 * @returns 包含起始位置和左侧元素初始宽度的对象
			 */
			function down(e: MouseEvent | TouchEvent): { startX: number; leftWidth: number } {
				// 获取鼠标或手指按下时的 X 坐标
				const startX = 'clientX' in e ? e.clientX : e.touches[0].clientX;
				// 获取左侧元素的初始宽度
				const leftWidth = leftComponent.offsetWidth;
				return { startX, leftWidth };
			}

			/**
			 * 鼠标或手指移动时的处理函数
			 * @param e 鼠标或触摸事件对象
			 * @param obj 包含起始位置和左侧元素初始宽度的对象
			 */
			function move(e: MouseEvent | TouchEvent, obj: { startX: number; leftWidth: number }) {
				const { startX, leftWidth } = obj;
				// 获取当前鼠标或手指的 X 坐标
				const currentX = 'clientX' in e ? e.clientX : e.touches[0].clientX;
				// 计算鼠标或手指移动的距离
				const diffX = currentX - startX;

				// 计算新的左侧元素宽度
				let newLeftWidth = leftWidth + diffX;
				// 获取父容器的宽度
				const containerWidth = (leftComponent.parentNode as HTMLElement).offsetWidth;
				// 计算新的右侧元素宽度
				let newRightWidth = containerWidth - newLeftWidth;

				// 确保新的宽度大于 0 且右侧元素宽度不超过最大宽度
				if (newLeftWidth > 0 && newRightWidth > 0) {
					if (newRightWidth > maxRightWidth) {
						newRightWidth = maxRightWidth;
						newLeftWidth = containerWidth - newRightWidth;
					}
					// 更新左侧元素的宽度
					leftComponent.style.width = `${newLeftWidth}px`;
					// 更新右侧元素的宽度
					rightComponent.style.width = `${newRightWidth}px`;
				}
			}

			// 禁止文本选中的函数
			function disableSelection() {
				const bodyStyle = document.body.style;
				bodyStyle.userSelect = 'none';
				(bodyStyle as any).webkitUserSelect = 'none';
				(bodyStyle as any).MozUserSelect = 'none';
				(bodyStyle as any).msUserSelect = 'none';
			}

			// 恢复文本选中的函数
			function enableSelection() {
				const bodyStyle = document.body.style;
				bodyStyle.userSelect = 'auto';
				(bodyStyle as any).webkitUserSelect = 'auto';
				(bodyStyle as any).MozUserSelect = 'auto';
				(bodyStyle as any).msUserSelect = 'auto';
			}
			// 使用 ResizeObserver 监听父元素尺寸变化
			const resizeObserver = new ResizeObserver(() => {
				el.style.height = `${parentElement.offsetHeight}px`;
			});
			resizeObserver.observe(parentElement);

			// 在元素卸载时停止监听
			(el as any).__resizeObserver = resizeObserver;

			// 添加公共方法用于修改高度
			(el as any).changeHeight = (height?: number) => {
				if (height !== undefined) {
					el.style.height = `${height}px`;
				} else {
					el.style.height = `${initialHeight}px`;
				}
			};
		},
		unmounted(el: HTMLElement) {
			const resizeObserver = (el as any).__resizeObserver;
			if (resizeObserver) {
				resizeObserver.disconnect();
				delete (el as any).__resizeObserver;
			}
		},
	});
}
